The following is the clsMaths class declaration is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UseDelegate
{
class clsMaths
{
public delegate int PointerMaths(int i, int y);//declare delegate
public PointerMaths getPointer(int intOperate) //definition delegate object
{
PointerMaths objpointer = null;
if (intOperate==1)
{
objpointer = Add;
}
else if (intOperate==2)
{
objpointer= Sub;
}
else if (intOperate==3)
{
objpointer = Multi;
}
else if (intOperate==4)
{
objpointer = Div;
}
return objpointer;
}
#region Maths Methods
private int Add(int i, int y)
{
return i + y;
}
private int Sub(int i, int y)
{
return i - y;
}
private int Multi(int i, int y)
{
return i * y;
}
private int Div(int i, int y)
{
return i / y;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace UseDelegate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
clsMaths objMath = new clsMaths();
int intOperatio = Convert.ToInt32(textBox3.Text);
int intNumber1 = Convert.ToInt32(textBox1.Text);
int intNumber2 = Convert.ToInt32(textBox2.Text);
int intResult =objMath.getPointer(intOperatio).Invoke(intNumber1, intNumber2); //Invoke:for delegate to call method
label1.Text= "Result Is:"+intResult.ToString();
}
}
}
Let's look atoperating results:
Leave Comment